package com.nb.customratingbar;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

/**
 * Version 1.0
 * Describe:自定义RatingBar
 */
class RatingBar extends View {
    private Bitmap mStarNormalBitmap;
    private Bitmap mStarFocusBitmap;
    private int mMarks;//满分多少分
    private int mCurrentMarks = 1;//当前分数 最低一分
    private int mInterval = 10;//星星之间的间隔

    public RatingBar(Context context) {
        this(context, null);
    }

    public RatingBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RatingBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RatingBar);
        int starNormalId = array.getResourceId(R.styleable.RatingBar_starNormal, R.mipmap.star_normal);
        mStarNormalBitmap = BitmapFactory.decodeResource(getResources(), starNormalId);
        int starFocusId = array.getResourceId(R.styleable.RatingBar_starFocus, R.mipmap.star_focus);
        mStarFocusBitmap = BitmapFactory.decodeResource(getResources(), starFocusId);
        mMarks = array.getInt(R.styleable.RatingBar_marks, 5);
        array.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getPaddingLeft() + mStarFocusBitmap.getWidth() * mMarks + mInterval * (mMarks - 1);//星星的宽度加上间隔
        int height = getPaddingTop() + mStarFocusBitmap.getHeight() + getPaddingBottom();

        setMeasuredDimension(width, height);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        int startWidth = mStarFocusBitmap.getWidth();
        for (int i = 0; i < mMarks; i++) {
            int left = getPaddingLeft() + i * startWidth + i * mInterval;
            int top = getPaddingTop();
            if (mCurrentMarks > i) {
                canvas.drawBitmap(mStarFocusBitmap, left, top, null);
            } else {
                canvas.drawBitmap(mStarNormalBitmap, left, top, null);
            }

        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                float moveX = event.getX();
                int marks = (int) ((moveX / (mStarFocusBitmap.getWidth() + mInterval)) + 1);
                if (marks != mCurrentMarks) {
                    mCurrentMarks = marks;
                    invalidate();
                }
        }

        return true;
    }
}
